package com.sx.gongzhong.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.compress.Luban;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.sx.gongzhong.BaseActivity;
import com.sx.gongzhong.R;
import com.sx.gongzhong.adapter.MultiImageAdapter;
import com.sx.gongzhong.model.LocationBean;
import com.sx.gongzhong.model.MsgEvent;
import com.sx.gongzhong.model.PhotoBean;
import com.sx.gongzhong.net.MyRxBus;
import com.sx.gongzhong.pest.DefendRoadAddPest;
import com.sx.gongzhong.pest.UploadFilePest;
import com.sx.gongzhong.utils.BaseUtil;
import com.sx.gongzhong.utils.ToastUtils;
import com.sx.gongzhong.view.IVoidView;
import com.sx.gongzhong.view.UploadFileView;
import com.sx.gongzhong.widget.CountEditText;
import com.sx.gongzhong.widget.LoadDialog;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 隐患新增
 */
public class DefendRoadAddActivity extends BaseActivity implements UploadFileView,IVoidView{

    @BindView(R.id.tv_Location)
    TextView tv_Location;
    @BindView(R.id.et_Content)
    CountEditText et_Content;
    @BindView(R.id.tv_Count)
    TextView tv_Count;
    @BindView(R.id.recyclerView)
    RecyclerView rvImageRV;
    private MultiImageAdapter adapter;
    private List<PhotoBean> selectList = new ArrayList<>();
    /**上传后的地址所选文件*/
    private List<String> fileList;
    private LocationBean locationBean;

    @Override
    public void setUI(Bundle savedInstanceState) {
        setContentView(R.layout.activity_defend_road_add);
        setTitleName(R.string.danger_add);
        setTitleRight(R.string.confirm);
        ButterKnife.bind(this);
        initViews();
    }

    private void initViews() {
        rvImageRV.setLayoutManager(new LinearLayoutManager(this, LinearLayout.HORIZONTAL, false));
        adapter = new MultiImageAdapter(this, mAddPicClickListener);
        adapter.setList(selectList);
        rvImageRV.setAdapter(adapter);
        et_Content.setOnEditTextCountLisener(new CountEditText.OnEditTextCountLisener() {
            @Override
            public void setCount(int currentCount) {
                tv_Count.setText(currentCount+"/500");
            }
        });
    }

    @OnClick({R.id.tv_right,R.id.tv_Location})
    public void OnClick(View view){
        switch (view.getId()){
            case R.id.tv_right:
               submit();
                break;
            case R.id.tv_Location:
                startActivityForResult(new Intent(this,LocationActivity.class),100);
                break;
        }
    }

    /**
     * 提交
     */
    private void submit() {
        if(locationBean==null){
            ToastUtils.showToast(this,"请选择位置");
            return;
        }
        String content=et_Content.getText().toString().trim();
        if (BaseUtil.isEmpty(content)){
            ToastUtils.showToast(this,"请输入内容");
            return;
        }
        if (selectList.size()>0){
            List<File> files = new ArrayList<>();
            for (PhotoBean localMedia : selectList) {
                files.add(new File(localMedia.getPath()));
            }
            LoadDialog.show(this, "正在上传图片...");
            new UploadFilePest(this).uploadFile(this, files);
        }else {
            submitDone();
        }
    }

    private void submitDone() {
        LoadDialog.show(this, "提交中");
        new DefendRoadAddPest(this).addDefendRoad(locationBean,
                et_Content.getText().toString().trim(),fileList);
    }

    //点击的添加文件的响应
    private MultiImageAdapter.AddPicClickListener mAddPicClickListener = new MultiImageAdapter.AddPicClickListener() {
        @Override
        public void onAddPicClick() {
            int max = 3 - selectList.size();
            if (max > 0) {
                PictureSelector.create(DefendRoadAddActivity.this)
                        .openGallery(PictureMimeType.ofImage())
                        .selectionMode(PictureConfig.MULTIPLE)
                        .maxSelectNum(max)// 最大图片选择数量 int
                        //.previewImage(true)// 是否可预览图片
                        .enableCrop(true)
                        .withAspectRatio(4, 3)
                        .compress(true)
                        .compressGrade(Luban.CUSTOM_GEAR)
                        .compressMaxKB(200)//压缩最大值kb compressGrade()为Luban.CUSTOM_GEAR有效 int
                        .forResult(PictureConfig.CHOOSE_REQUEST);
            } else {
                ToastUtils.showToast(DefendRoadAddActivity.this, "最多上传3张");
            }
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST://选图片
                    List<LocalMedia> picUrls = PictureSelector.obtainMultipleResult(data);
                    if (!picUrls.isEmpty()) {
                        for (LocalMedia localMedia : picUrls) {
                            String path = localMedia.getCompressPath();
                            String type = path.substring(path.lastIndexOf("."));
                            selectList.add(new PhotoBean(path, type));
                        }
                        if (adapter != null) adapter.notifyDataSetChanged();
                    }
                    break;
                case 100://位置选择
                    locationBean= (LocationBean) data.getSerializableExtra("Location");
                    if (locationBean!=null){
                        tv_Location.setText(locationBean.getAddress());
                    }
                    break;
            }
        }
    }

    @Override
    public void showError(String message) {
        LoadDialog.dismiss(this);
        ToastUtils.showToast(this,message);
    }

    @Override
    public void uploadSuccess(List<PhotoBean> beans) {
        if(fileList==null){
            fileList=new ArrayList<>();
        }
        for (PhotoBean bean:beans){
            fileList.add(bean.getId());
        }
        submitDone();
    }

    @Override
    public void voidView(String string) {
        LoadDialog.dismiss(this);
        ToastUtils.showToast(this,string);
        MyRxBus.get().post(new MsgEvent("DefendRoad",1,null));
        finish();
    }
}
